﻿using Account.Api.Client;
using Account.Api.Dtos;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CyssBlazor.Shared.Pages.AccountManager.Menus
{
    public partial class PermissionList
    {
        [CascadingParameter(Name = "BodyContext")]
        private object ObjectModel { set; get; }

        private MenuModel ParentMenu
        {
            get
            {
                return (ObjectModel as MenuModel);

            }
        }

        protected async override Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                if (ObjectModel != null)
                {
                    //Model.MenuId = ParentMenu.Id;
                    //Model.MenuName = ParentMenu.Name;
                    await InvokeAsync(StateHasChanged);
                }
            }
            await base.OnAfterRenderAsync(firstRender);
        }

        private MenuModel CurrentMenuModel { set; get; }

        public PermissionSearchModel searchModel { set; get; } = new PermissionSearchModel();


        /// <summary>
        ///数据查询方法
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        protected async Task<QueryData<PermissionModel>> OnQueryAsync(QueryPageOptions options)
        {
            //TODO: 此处代码后期精简
            searchModel.pageIndex = options.PageIndex;
            searchModel.pageSize = options.PageItems;
            searchModel.MenuId = ParentMenu.Id;
            var apiResponse = await AccountClientFactory.Permission.GetPageListPermissions(searchModel);
            if (apiResponse.IsSuccess && apiResponse.Data != null)
            {
                return await Task.FromResult(new QueryData<PermissionModel>()
                {
                    Items = apiResponse.Data.Data,
                    TotalCount = apiResponse.Data.Total
                });
            }
            return null;
        }

        protected async Task<bool> OnSaveAsync(PermissionModel options, ItemChangedType itemChangedType)
        {
            if (options.Id == 0)
            {
                options.MenuId = ParentMenu.Id;
                var apiResponse = await AccountClientFactory.Permission.CreatePermission(options);
                return apiResponse.IsSuccess;
            }
            else
            {
                var apiResponse = await AccountClientFactory.Permission.EditPermission(options);
                return apiResponse.IsSuccess;
            }
        }

        protected async Task<bool> OnDeleteAsync(IEnumerable<PermissionModel> options)
        {
            var apiResponse = await AccountClientFactory.Permission.DeletePermission(options.FirstOrDefault().Id);
            return apiResponse.IsSuccess;
        }

    }

}
